#include "Server.hpp"
#include <memory>
void Usage(const char *str)
{
    cout << "Usage:" << endl
         << str << "  port\n"
         << endl;
}
void cal(Request &req, Response &resp)
{
    int result = 0, exitcode = 0;
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;
        break;
    case '*':
        resp._result = req._x * req._y;
        break;
    case '/':
        if (req._y == 0)
        {
            resp._result = 0;
            resp._exitcode = -1;
        }
        else
            resp._result = req._x / req._y;
        break;
    default:
        break;
    }
    if (resp._exitcode != -1)
    {
        resp._exitcode = 0;
    }
}
void server(Connection *conn)
{
    string package;
    if (recvPackage(conn->_fd, conn->_inbuffer, package))
    {
        string text;
        if (!deLength(package, text))
        {
            logMessage(ERROR, "deLength fail");
            return;
        }
        Request req;
        req.deserialize(text);
        logMessage(NORMAL, "正文：%s", text.c_str());
        Response resp;
        cal(req, resp);
        string buffer;
        resp.serialize(buffer);
        logMessage(NORMAL, "结果: %s", buffer.c_str());
        if (!enLength(buffer))
        {
            logMessage(ERROR, "enLength fail");
            return;
        }
        conn->_outbuffer = buffer;
        conn->_write(conn);
    }
}
int main(int argc, const char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }
    unique_ptr<Server> tsvr(new Server(atoi(argv[1]), server));
    tsvr->init();
    tsvr->start();
    return 0;
}